const mysql=require('mysql2/promise'),
log=console.log,
{con}=require('./common.js');

async function likeState(userId,id){
    let sql = '';
    let [rows] = '';
    //查找语句条数
    const sql1 = `SELECT max(unid) as length FROM user.like`;
    let length = await con.execute(sql1);
    length = length[0][0].length + 1;
    const sql2 = `SELECT count(unid) as count FROM user.like where userId='${userId}' AND passageId='${id}'`;
    let count = await con.execute(sql2);
    count = count[0][0].count;
    //获取现在时间
    if(count != 0){
        console.log(11);
        sql = `SELECT unid FROM user.like where userId='${userId}' AND passageId='${id}'`;
        [rows] = await con.execute(sql);
        sql = `update user.essay set essay.like=essay.like-1 where id='${id}';`
        await con.execute(sql);
    }
    else{
        console.log(22);
        let date=new Date();
        function formatDate(times) {
            var date = new Date(times);
            var year = date.getFullYear(); //年份
            var month = date.getMonth() + 1; //月份
            var day = date.getDate(); //日
            var hour = function () { //获取小时
                return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            }
            var minute = function () { //获取分钟
                return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            }
        
            var second = function () { //获取秒数
                return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            }
            return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
        
        }
        date=formatDate(date)
        sql = `insert into user.like values(${length},'${userId}','${id}','${date}','true')`
        await con.execute(sql);
        sql = `update user.essay set essay.like=essay.like+1 where id='${id}';`
        await con.execute(sql);
    }
    // sql = `SELECT unid FROM user.like where userId=${userId} AND passageId=${id}`;
    // let [rows] = await con.execute(sql);
    return rows;
}

async function deleteId(id){
    const sql = `delete FROM user.like where unid='${id}'`;
    let [rows] = await con.execute(sql);
}

module.exports={likeState,deleteId}